package utils;

import book.Book;
import com.bit.utils.FileUtils;

import java.time.LocalDate;

import static constant.Constant.ALL_BOOK_FILE_NAME;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 87111
 * Date: 2025-08-23
 * Time: 20:36
 */
public class AnalyzingBook {
    //对指定文件写入操作
    public void writeObject(Book[] books, String filename) {
        //获取books数组实际有几本书
        int bookNum = 0;
        for(int i = 0; i < books.length; i++) {
            if(books[i] != null) {
                bookNum++;
            }
        }
        //将数组中的对象存储到字符串中
        StringBuilder booksString = new StringBuilder();
        for (int i = 0; i < bookNum; i++) {
            if(books[i] != null) {
                booksString.append(books[i].toJson());
                if(i != bookNum -1 ) {
                    booksString.append("\n");
                }
            }
        }
        FileUtils.writeFile(booksString.toString(), filename);
    }

    //对指定文件进行读取操作
    public Book[] readObject(String filename) {
        //从文件中读取数据
        String chs = FileUtils.readFile(filename);
        if(chs == null || chs.isEmpty()) {
            System.out.println(filename + "文件是空的或者没有指向对象");
            return null;
        }
        //将字符串按照\n分割
        String[] booksString = chs.split("\n");
        //将对象存储到数组里
        Book[] bookList = new Book[booksString.length];
        for (int i = 0; i < booksString.length; i++) {
            Book book = parseBookString(booksString[i]);
            bookList[i] = book;
        }
        return bookList;
    }

    //将读取的字符串解析为对象
    public Book parseBookString(String bookString) {
        //检查是否为空
        if(bookString == null) {
            return null;
        }
        //使用逗号分隔字符串
        String[] book = bookString.split(",");
        //字符串转化类型
        int bookId = Integer.parseInt(book[0]); //书Id
        String bookName = book[1];   //书名
        String author = book[2];  //作者
        String category = book[3];    //类别
        int publishYear = Integer.parseInt(book[4]);    //出版年份
        boolean isBorrowed = Boolean.parseBoolean(book[5]); //借阅状态
        int borrowCount = Integer.parseInt(book[6]);    //借阅次数
        LocalDate shelfDate = LocalDate.parse(book[7]);    //上架时间
        //创建对象
        if(bookName != null && author != null && category != null && shelfDate != null) {
            Book book1 = new Book(bookName, author, category, publishYear, shelfDate);
            book1.setBookId(bookId);
            book1.setIsBorrowed(isBorrowed);
            book1.setBorrowCount(borrowCount);
            return book1;
        }
        return null;
    }
}
